package com.aabte.commons.json;

import java.io.Reader;
import java.lang.reflect.Type;
import java.util.ServiceLoader;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/5
 */
public final class JSONUtils {

  private static JSONSerializationAdapter JSON_ADAPTER;

  static {

    ServiceLoader<JSONSerializationAdapter> load = ServiceLoader
        .load(JSONSerializationAdapter.class);

    JSONSerializationAdapter jsonSerializationAdapter = null;
    for (JSONSerializationAdapter adapter : load) {
      if (null != adapter) {
        jsonSerializationAdapter = adapter;
        break;
      }
    }

    if (null == jsonSerializationAdapter) {
      throw new SerializationAdapterInitializeException(
          "Provider for " + JSONSerializationAdapter.class.getName() + " cannot be found.");
    }
    JSON_ADAPTER = jsonSerializationAdapter;
  }

  private JSONUtils() {
  }

  public static JSONSerializationAdapter getJsonAdapter() {
    return JSON_ADAPTER;
  }

  public static void setJsonAdapter(JSONSerializationAdapter jsonAdapter) {
    JSON_ADAPTER = jsonAdapter;
  }

  public static String toJson(Object src) throws JSONException {
    return JSON_ADAPTER.toJson(src);
  }

  public static String toJson(Object src, Type typeOfSrc) throws JSONException {
    return JSON_ADAPTER.toJson(src, typeOfSrc);
  }

  public static void toJson(Object src, Appendable writer) throws JSONIOException {
    JSON_ADAPTER.toJson(src, writer);
  }

  public static <T> T fromJson(String json, Class<T> classOfT) throws JSONSyntaxException {
    return JSON_ADAPTER.fromJson(json, classOfT);
  }

  public static <T> T fromJson(String json, Class<T> classOfT, Class<?>... genericParams)
      throws JSONSyntaxException {
    return JSON_ADAPTER.fromJson(json, classOfT, genericParams);
  }

  public static <T> T fromJsonArray(String json, Class<?> genericParam) throws JSONSyntaxException {
    return JSON_ADAPTER.fromJsonArray(json, genericParam);
  }

  public static <T> T fromJson(Reader json, Class<T> classOfT) throws JSONSyntaxException {
    return JSON_ADAPTER.fromJson(json, classOfT);
  }

  public static <T> T fromJson(Reader json, Type typeOfT) throws JSONSyntaxException {
    return JSON_ADAPTER.fromJson(json, typeOfT);
  }
}
